package com.jiukuaidao.zhulin.util;

import android.text.TextUtils;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.jiukuaidao.library.Config;
import com.jiukuaidao.library.net.MyLoggerInterceptor;
import com.jiukuaidao.zhulin.api.ApiManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author : H_Joker
 * Date : 2016/5/13
 * Description : 默认OkHttpClient包含 log打印、header拼公参、Stetho监控 功能
 */
public class RetrofitUtil {

    private RetrofitUtil() {
    }

    /**
     * 获取 上传图片默认APImanager
     *
     * @return
     */
    public static ApiManager getUploadPicManager() {
        return getApiManager(Config.URLConfig.BASE_IMAGE_URL, null, null, null);
    }

    /**
     * 获取 默认APIManager
     *
     * @param oriParams 原始参数
     * @return
     */
    public static ApiManager getApiManager(TreeMap<String, String> oriParams) {
        return getApiManager(null, null, oriParams, null);
    }

    /**
     * 获取带返回值监听器的默认APIManager
     *
     * @param oriParams
     * @param resInterListener
     * @return
     */
    public static ApiManager getApiManager(TreeMap<String, String> oriParams, MyLoggerInterceptor.ResInterListener resInterListener) {
        return getApiManager(null, null, oriParams, resInterListener);
    }

    /**
     * 获取 APIManager
     *
     * @param baseUrl      自定义BaseURL
     * @param okHttpClient 自定义OkHttpClient
     * @param oriParams    原始参数
     * @return
     */
    public static ApiManager getApiManager(String baseUrl, OkHttpClient okHttpClient, final TreeMap<String, String> oriParams) {
        return getApiManager(baseUrl, okHttpClient, oriParams, null);
    }

    /**
     * 获取 APIManager
     *
     * @param baseUrl          自定义BaseURL
     * @param okHttpClient     自定义OkHttpClient
     * @param oriParams        原始参数
     * @param resInterListener 返回数据监听器
     * @return
     */
    public static ApiManager getApiManager(String baseUrl, OkHttpClient okHttpClient, final TreeMap<String, String> oriParams, MyLoggerInterceptor.ResInterListener resInterListener) {
        ApiManager apiManager;
        if ((!Config.URLConfig.BASE_URL.equals(baseUrl) && !TextUtils.isEmpty(baseUrl)) || okHttpClient != null) {// 需要自定义retrofit
            apiManager = getRetrofit(baseUrl, okHttpClient, oriParams, resInterListener).create(ApiManager.class);
        } else {
            apiManager = getRetrofit(null, null, oriParams, resInterListener).create(ApiManager.class);
        }

        return apiManager;
    }

    /**
     * 获取 Retrofit
     *
     * @param baseUrl          自定义BaseURL
     * @param okhttpClient     自定义OkHttpClient
     * @param oriParams        原始参数
     * @param resInterListener 返回数据监听器
     * @return
     */
    private static Retrofit getRetrofit(String baseUrl, OkHttpClient okhttpClient, TreeMap<String, String> oriParams, MyLoggerInterceptor.ResInterListener resInterListener) {
        Retrofit retrofit;
        if ((!Config.URLConfig.BASE_URL.equals(baseUrl) && !TextUtils.isEmpty(baseUrl)) || okhttpClient != null) {// 需要自定义retrofit
            retrofit = getBuilder(baseUrl, okhttpClient, oriParams, resInterListener).build();
        } else {
            retrofit = getBuilder(null, null, oriParams, resInterListener).build();
        }
        return retrofit;
    }

    /**
     * 获取 Builder
     *
     * @param baseUrl          自定义BaseURL
     * @param okhttpClient     自定义OkHttpClient
     * @param oriParams        原始参数
     * @param resInterListener 返回数据监听器
     * @return
     */
    private static Retrofit.Builder getBuilder(String baseUrl, OkHttpClient okhttpClient, TreeMap<String, String> oriParams, MyLoggerInterceptor.ResInterListener resInterListener) {
        Retrofit.Builder builder;
        if (!Config.URLConfig.BASE_URL.equals(baseUrl) && !TextUtils.isEmpty(baseUrl)) {// 如果不是自己的基地址
            builder = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .callFactory(getOkClient(okhttpClient, oriParams, false, null))
                    .addConverterFactory(GsonConverterFactory.create());
        } else {// 用自己的基地址
            if (okhttpClient != null) {// 自定义OkHttp
                builder = new Retrofit.Builder()
                        .baseUrl(Config.URLConfig.BASE_URL)
                        .callFactory(getOkClient(okhttpClient, oriParams, false, resInterListener))
                        .addConverterFactory(GsonConverterFactory.create());
            } else {// 默认Builder
                builder = new Retrofit.Builder()
                        .baseUrl(Config.URLConfig.BASE_URL)
                        .callFactory(getOkClient(null, oriParams, true, resInterListener))
                        .addConverterFactory(GsonConverterFactory.create());
            }
        }
        return builder;
    }

    /**
     * 获取 OkHttpClient
     *
     * @param okhttpClient     自定义OkHttpClient
     * @param oriParams        原始参数
     * @param needBaseParam    是否需要拼写公参
     * @param resInterListener 返回数据监听器
     * @return
     */
    private static OkHttpClient getOkClient(OkHttpClient okhttpClient, TreeMap<String, String> oriParams, boolean needBaseParam, MyLoggerInterceptor.ResInterListener resInterListener) {
        OkHttpClient client;
        MyLoggerInterceptor mMyLoggerInterceptor;
        if (okhttpClient != null) {
            client = okhttpClient;
        } else if (!needBaseParam) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            mMyLoggerInterceptor = new MyLoggerInterceptor(Config.URLConfig.TAG, true);
            mMyLoggerInterceptor.setListener(resInterListener);
            builder.addInterceptor(mMyLoggerInterceptor);

            if (Config.Debug) {
                builder.addNetworkInterceptor(new StethoInterceptor());
            }

            client = builder.build();
        } else {
            mMyLoggerInterceptor = new MyLoggerInterceptor(Config.URLConfig.TAG, true);
            mMyLoggerInterceptor.setListener(resInterListener);

            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .addInterceptor(getBaseParamInter(oriParams))
                    .addInterceptor(mMyLoggerInterceptor);

            if (Config.Debug) {
                builder.addNetworkInterceptor(new StethoInterceptor());
            }

            client = builder.build();
        }
        return client;
    }

    /**
     * 文件下载工具
     *
     * @param url          下载链接
     * @param fileCallBack 下载回调
     */
    public static void downLoadFile(String url, FileCallBack fileCallBack) {
        if (!TextUtils.isEmpty(url) && fileCallBack != null) {
            OkHttpUtils.get()
                    .url(url)
                    .build()
                    .execute(fileCallBack);
        }
    }

    /**
     * 获取拼写公参Interceptor
     *
     * @param oriParams 原始参数
     * @return
     */
    private static Interceptor getBaseParamInter(final TreeMap<String, String> oriParams) {
        Interceptor mDefaultBaseParamInter = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request request = chain.request();

                TreeMap<String, String> baseParam = NetUtil.getBaseParam(getUrl(request), getHeaders(request), getMethod(request), getContent(request));

                Request.Builder builder = chain.request().newBuilder();

                Iterator<Map.Entry<String, String>> entryIterator = baseParam.entrySet().iterator();
                while (entryIterator.hasNext()) {
                    Map.Entry<String, String> entry = entryIterator.next();
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
                builder.addHeader("Accept", "application/json");
                return chain.proceed(builder.build());
            }

            private String bodyToString(final Request request) {
                try {
                    final Request copy = request.newBuilder().build();
                    final Buffer buffer = new Buffer();
                    copy.body().writeTo(buffer);
                    return buffer.readUtf8();
                } catch (final IOException e) {
                    return "something error when show requestBody.";
                }
            }

            private boolean isText(MediaType mediaType) {
                if (mediaType.type() != null && mediaType.type().equals("text")) {
                    return true;
                }
                if (mediaType.subtype() != null) {
                    if (mediaType.subtype().equals("json") ||
                            mediaType.subtype().equals("xml") ||
                            mediaType.subtype().equals("html") ||
                            mediaType.subtype().equals("webviewhtml")
                            )
                        return true;
                }
                return false;
            }

            private String getUrl(Request request) {
                return request.url().toString();
            }

            private Map<String, List<String>> getHeaders(Request request) {
                Headers headers = request.headers();
                Map<String, List<String>> map = new HashMap<>();
                if (headers != null) {
                    Map<String, List<String>> headerMap = headers.toMultimap();
                    for (Map.Entry<String, List<String>> entry : headerMap.entrySet()) {
                        map.put(entry.getKey(), entry.getValue());
                    }
                }
                return map;
            }

            private String getMethod(Request request) {
                return request.method();
            }

            private String getContent(Request request) {
                RequestBody requestBody = request.body();
                if (requestBody != null) {
                    MediaType mediaType = requestBody.contentType();
                    if (mediaType != null) {
                        if (isText(mediaType)) {
                            return bodyToString(request);
                        }
                    }
                }
                return null;
            }
        };

        return mDefaultBaseParamInter;
    }

}
